package patrol.mobile.com.mobilepatrol.activity.route_query;

import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.DBHelper;
import patrol.mobile.com.mobilepatrol.PatrolApp;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.SPUtils;
import patrol.mobile.com.mobilepatrol.view.RouteManageView;

/**
 * Created by apple on 17/9/27.
 */

public class RouteManagePer {
    private RouteManageView mView;

    public RouteManagePer(RouteManageView mView) {
        this.mView = mView;
    }

    public void getRoutes() {
        OkHttpUtils
                .post()
                .url(SPUtils.get(Constants.current_ser,"") + Urls.getRouteManage)
                .addParams("orgId", UserManager.getOrgNo())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mView.hideLoading();
                        mView.onRouteManageError(e.getMessage());
                    }
                    @Override
                    public void onResponse(String response, int id) {

                        try {
                        JSONObject object = new JSONObject(response);
                        if (object.getInt("state")==200){
                            mView.hideLoading();
//                            RouteDataManager.delRoutes();
                            final JSONArray array = object.getJSONArray("routeMangeList");
                            List<RouteManage> data = GsonUtil.jsonToList(array.toString(),RouteManage.class);
                            DBHelper db = new DBHelper(PatrolApp.context);
                            db.insertRouteManage(data);
                            db.close();
//                                PatrolApp.realm.executeTransaction(new Realm.Transaction() {
//                                    @Override
//                                    public void execute(Realm realm) {
//                                        realm.createAllFromJson(RouteManage.class, array.toString());
//                                    }
//                                });
                            mView.onRouteManageSuccess("初始路线查询成功");
                        }else{
                            mView.onRouteManageError("初始化路线查询失败");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    }

                });
    }
}
